package com.hdu.other.dp.treeDP;

import jdk.nashorn.internal.ir.Terminal;

public class lc979 {


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public int distributeCoins(TreeNode root) {
            return f(root).moveCnt;
        }

        Info f(TreeNode x) {
            if (x == null) {
                return new Info(0, 0, 0);
            }
            Info left = f(x.left);
            Info right = f(x.right);

            int nodeCnt = left.nodeCnt + right.nodeCnt + 1;
            int coinCnt = left.coinCnt + right.coinCnt + x.val;
            int moveCnt = left.moveCnt + right.moveCnt
                    + Math.abs(left.coinCnt - left.nodeCnt)
                    + Math.abs(right.coinCnt - right.nodeCnt);

            return new Info(nodeCnt, coinCnt, moveCnt);
        }

        class Info {
            int nodeCnt;
            int coinCnt;
            int moveCnt;

            public Info(int nodeCnt, int coinCnt, int moveCnt) {
                this.nodeCnt = nodeCnt;
                this.coinCnt = coinCnt;
                this.moveCnt = moveCnt;
            }
        }

    }
}
